import React, { useState } from 'react'
import { Card, Form, Input, Switch, Button, message, Tabs } from 'antd'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getAuthConfig, updateAuthConfig } from '../api/gateway'

export default function AuthConfig() {
  const [form] = Form.useForm()
  const queryClient = useQueryClient()
  const [activeTab, setActiveTab] = useState('jwt')

  const { data: config, isLoading } = useQuery({
    queryKey: ['authConfig'],
    queryFn: getAuthConfig,
  })

  // 当数据加载成功后设置表单值
  React.useEffect(() => {
    if (config) {
      form.setFieldsValue(config)
    }
  }, [config, form])

  const updateMutation = useMutation({
    mutationFn: updateAuthConfig,
    onSuccess: () => {
      message.success('配置更新成功')
      queryClient.invalidateQueries({ queryKey: ['authConfig'] })
    },
    onError: () => {
      message.error('配置更新失败')
    },
  })

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      updateMutation.mutate(values)
    } catch (error) {
      console.error('Validation failed:', error)
    }
  }

  if (isLoading) {
    return <div>加载中...</div>
  }

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>认证配置</h1>
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.TabPane tab="JWT 配置" key="jwt">
            <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
              <Form.Item
                name={['jwt', 'secret']}
                label="JWT 密钥"
                rules={[{ required: true, message: '请输入 JWT 密钥' }]}
              >
                <Input.Password placeholder="输入 JWT 密钥" />
              </Form.Item>
              <Form.Item
                name={['jwt', 'issuer']}
                label="签发者"
                rules={[{ required: true, message: '请输入签发者' }]}
              >
                <Input placeholder="api-gateway" />
              </Form.Item>
              <Form.Item
                name={['jwt', 'expiration']}
                label="过期时间（秒）"
                rules={[{ required: true, message: '请输入过期时间' }]}
              >
                <Input type="number" placeholder="7200" />
              </Form.Item>
              <Form.Item
                name={['jwt', 'refresh_expiration']}
                label="刷新令牌过期时间（秒）"
                rules={[{ required: true, message: '请输入刷新令牌过期时间' }]}
              >
                <Input type="number" placeholder="604800" />
              </Form.Item>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane tab="OAuth2 配置" key="oauth2">
            <Form form={form} layout="vertical" style={{ maxWidth: 600 }}>
              <Form.Item name={['oauth2', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
              <Form.Item label="GitHub">
                <Input.Group compact>
                  <Form.Item
                    name={['oauth2', 'providers', 'github', 'client_id']}
                    style={{ width: '50%', marginRight: 8 }}
                  >
                    <Input placeholder="Client ID" />
                  </Form.Item>
                  <Form.Item
                    name={['oauth2', 'providers', 'github', 'client_secret']}
                    style={{ width: '50%' }}
                  >
                    <Input.Password placeholder="Client Secret" />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item label="Google">
                <Input.Group compact>
                  <Form.Item
                    name={['oauth2', 'providers', 'google', 'client_id']}
                    style={{ width: '50%', marginRight: 8 }}
                  >
                    <Input placeholder="Client ID" />
                  </Form.Item>
                  <Form.Item
                    name={['oauth2', 'providers', 'google', 'client_secret']}
                    style={{ width: '50%' }}
                  >
                    <Input.Password placeholder="Client Secret" />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            </Form>
          </Tabs.TabPane>
        </Tabs>
        <Button
          type="primary"
          onClick={handleSubmit}
          loading={updateMutation.isLoading}
          style={{ marginTop: 16 }}
        >
          保存配置
        </Button>
      </Card>
    </div>
  )
}

